﻿using NewLife;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Kinlo.MESDocking
{
    public static class HttpHelper
    {
        public static (bool, string) Post(this string parameter, string url, int outtime, int reconnect_count)
        {
            while (reconnect_count > 0)
            {
                try
                {
                    HttpWebRequest request = WebRequest.CreateHttp(url);
                    request.ContentType = "application/json";
                    request.Method = "POST";
                    request.ProtocolVersion = HttpVersion.Version11;
                    request.Timeout = outtime;
                    //Match host = Regex.Match(url, _urlRegex);
                    //request.Host = host.Value;
                    byte[] bytes = Encoding.UTF8.GetBytes(parameter);
                    request.ContentLength = bytes.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(bytes, 0, bytes.Length);
                    }
                    var response = request.GetResponse();
                    byte[] byte1 = new byte[2048];
                    int length = 0;
                    using (Stream stream = response.GetResponseStream())
                    {
                        length = stream.Read(byte1, 0, 2048);
                    }
                    return new (true, Encoding.UTF8.GetString(byte1.Take(length).ToArray()));
                }
                catch (Exception ex)
                {
                    reconnect_count--;
                    if (reconnect_count == 0)
                    {
                        return new (false, ex.ToString());
                    }
                }
            }
            return new(false, "执行错误");
        }

        public static System.Text.Json.JsonSerializerOptions Options
        {
            get => new System.Text.Json.JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };
        }
    }
}
